package com.cardone.platform.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cardone.common.Characters;
import com.cardone.context.Contexts;
import com.cardone.platform.authority.service.NavigationService;
import com.cardone.platform.common.dto.EntityFileDto;
import com.cardone.platform.common.util.EntityFileUtils;
import com.cardone.platform.configuration.service.ConfigurationService;

/**
 * @author yaohaitao
 */
@Controller
@RequestMapping("/")
@Slf4j
public class IndexController {
	/**
	 * 配置服务
	 */
	@Qualifier(ConfigurationService.BEAN_ID)
	@Autowired(required = false)
	private ConfigurationService configurationService;

	/**
	 * 导航服务
	 */
	@Qualifier(NavigationService.BEAN_ID)
	@Autowired(required = false)
	private NavigationService navigationService;

	@RequestMapping(value = { "/entityFile/{filename}.{extension}" })
	public void entityFile(final HttpServletResponse response, @PathVariable("filename") String filename, @PathVariable("extension") final String extension) throws Exception {
		if (StringUtils.isNotBlank(extension)) {
			filename += Characters.dot.stringValue() + extension;
		}

		EntityFileUtils.writeTo(response, filename);
	}

	/**
	 * 上传界面
	 *
	 * @return 上传界面模板路径
	 */
	@RequestMapping(value = { "upload.html" })
	public void upload(final HttpServletRequest request, final EntityFileDto uploadEntityFile, final Model model) {
		try {
			final List<EntityFileDto> entityFileList = EntityFileUtils.upload(request, uploadEntityFile);

			if (!CollectionUtils.isEmpty(entityFileList)) {
				model.addAttribute("fileUrl", "/entityFile/" + entityFileList.get(0).getFilename());
				model.addAttribute("filename", entityFileList.get(0).getFilename());
			}
		} catch (final Exception e) {
			model.addAttribute(Contexts.message.stringValue(), e.getMessage());

			IndexController.log.debug(e.getMessage(), e);
		}
	}
}